// Deepseek AI聊天功能
class AIChatWidget {
    constructor(options = {}) {
        this.apiUrl = options.apiUrl || 'https://api.deepseek.com/v1/chat/completions';
        this.apiKey = options.apiKey || 'sk-980ecc7694e14620a29b5d679a3d1c05';
        
        // 获取DOM元素
        this.chatBody = document.getElementById('chatBody');
        this.userInput = document.getElementById('userInput');
        this.sendBtn = document.getElementById('sendBtn');
        
        // 绑定事件
        this.sendBtn.addEventListener('click', () => this.sendMessage());
        this.userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendMessage();
            }
        });
    }

    // 添加用户消息
    addUserMessage(message) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'chat-message user-message';
        messageDiv.innerHTML = `
            <div class="message-bubble user-bubble">
                ${message}
            </div>
        `;
        this.chatBody.appendChild(messageDiv);
        this.chatBody.scrollTop = this.chatBody.scrollHeight;
    }

    // 添加AI消息容器（用于流式响应）
    createAIMessageContainer() {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'chat-message ai-message';
        
        const bubbleDiv = document.createElement('div');
        bubbleDiv.className = 'message-bubble ai-bubble';
        messageDiv.appendChild(bubbleDiv);
        
        this.chatBody.appendChild(messageDiv);
        this.chatBody.scrollTop = this.chatBody.scrollHeight;
        
        return bubbleDiv;
    }

    // 解析SSE数据
    parseSSEData(data) {
        if (data === '[DONE]') return { done: true };
        
        try {
            const parsedData = JSON.parse(data);
            return {
                done: false,
                content: parsedData.choices[0].delta.content || ''
            };
        } catch (error) {
            console.error('解析SSE数据时出错:', error);
            return { done: false, content: '' };
        }
    }

    // 获取AI回复 - 使用流式响应
    async getAIStreamResponse(userMessage, messageContainer) {
        try {
            const requestData = {
                model: 'deepseek-chat',
                messages: [
                    {
                        role: 'system',
                        content: '你是创新科技的AI助手，负责回答用户关于公司产品和服务的问题。公司产品包括智能手表、智能音箱和无线耳机等。请提供专业、友好的回答。'
                    },
                    {
                        role: 'user',
                        content: userMessage
                    }
                ],
                temperature: 0.7,
                max_tokens: 500,
                stream: true
            };
            
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${this.apiKey}`,
                    'Accept': 'text/event-stream'
                },
                body: JSON.stringify(requestData)
            });
            
            if (!response.ok) {
                throw new Error(`API调用失败: ${response.status}`);
            }
            
            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');
            let buffer = '';
            
            while (true) {
                const { done, value } = await reader.read();
                
                if (done) {
                    break;
                }
                
                const chunk = decoder.decode(value, { stream: true });
                buffer += chunk;
                
                const lines = buffer.split('\n');
                buffer = lines.pop() || '';
                
                for (const line of lines) {
                    if (line.trim() === '' || !line.startsWith('data:')) continue;
                    
                    const data = line.slice(5).trim();
                    const parsedData = this.parseSSEData(data);
                    
                    if (parsedData.done) continue;
                    
                    if (parsedData.content) {
                        messageContainer.textContent += parsedData.content;
                        this.chatBody.scrollTop = this.chatBody.scrollHeight;
                    }
                }
            }
            
        } catch (error) {
            console.error('调用Deepseek API时出错:', error);
            messageContainer.textContent += '\n\n抱歉，我暂时无法回答您的问题。请稍后再试或联系客服。';
            this.chatBody.scrollTop = this.chatBody.scrollHeight;
        }
    }

    // 发送消息
    async sendMessage() {
        const message = this.userInput.value.trim();
        if (message) {
            this.addUserMessage(message);
            this.userInput.value = '';
            
            const aiMessageContainer = this.createAIMessageContainer();
            await this.getAIStreamResponse(message, aiMessageContainer);
        }
    }
}

// 导出类
window.AIChatWidget = AIChatWidget;